from wordcloud import WordCloud, ImageColorGenerator
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
import jieba
import jieba.analyse
import random


def simple():
    # 打开文本
    text = open('e:\\库存房源.txt').read()
    # 生成图像
    wc = WordCloud().generate(text)

    # 显示词云
    plt.imshow(wc, interpolation='bilinear')
    plt.axis('off')
    plt.show()


def chinese():
    # 打开文本
    text = open('E:\\西游记.txt', encoding='utf-8').read()
    # 生成对象
    wc = WordCloud(font_path='YiPinQingYeShouXieTi-2.ttf', width=800, height=600, mode='RGBA',
                   background_color=None).generate(text)

    # 显示词云
    plt.imshow(wc, interpolation='bilinear')
    plt.axis('off')
    plt.show()

    # 保存到文件
    # wc.to_file('wordcloud.png')


# 蒙版
def mask():
    # 打开文本
    text = open('e:\\西游记.txt', encoding='utf-8').read()

    # 中午分词
    text = " ".join(jieba.cut(text))

    # 生成对象
    mask = np.array(Image.open("e:\\meinv.png"))
    wc = WordCloud(mask=mask, font_path='YiPinQingYeShouXieTi-2.ttf', mode='RGBA', background_color=None).generate(text)

    # 显示词云
    plt.imshow(wc, interpolation='bilinear')
    plt.axis('off')
    plt.show()


def random_color(word, font_size, position, orientation, font_path, random_state):
    s = 'hsl(0,%d%%,%d%%)' % (random.randint(60, 80), random.randint(60, 80))
    return s


def color():
    # 打开文件
    text = open('e:\\西游记.txt', encoding='utf-8').read()
    text = " ".join(jieba.cut(text))
    mask = np.array(Image.open('e:\\meinv.png'))
    wc = WordCloud(mask=mask, font_path='YiPinQingYeShouXieTi-2.ttf', mode='RGBA', background_color=None).generate(text)

    # 使用图片颜色
    img_color = ImageColorGenerator(mask)
    # wc.recolor(color_func=img_color)

    # 纯色
    wc.recolor(color_func=random_color)

    plt.imshow(wc, interpolation='bilinear')
    plt.axis('off')
    plt.show()


def detail_control():
    # 打开文本
    text = open('e:\\西游记.txt', encoding='utf-8').read()

    # 提取关键词和权重
    freq = jieba.analyse.extract_tags(text, topK=200, withWeight=True)
    print(freq[:20])
    freq = {i[0]: i[1] for i in freq}

    # 生成对象
    mask = np.array(Image.open("e:\\meinv.png"))
    wc = WordCloud(mask=mask, font_path='YiPinQingYeShouXieTi-2.ttf', mode='RGBA', background_color=None).generate_from_frequencies(freq)

    # 从图片中生成颜色
    image_colors = ImageColorGenerator(mask)
    wc.recolor(color_func=image_colors)

    # 显示词云
    plt.imshow(wc, interpolation='bilinear')
    plt.axis("off")
    plt.show()


if __name__ == '__main__':
    # simple()
    # chinese()
    # mask()
    # color()
    detail_control()
